//
//  HelperTableViewController.m
//  CarWorld
//
//  Created by 李东方 on 15/3/28.
//  Copyright (c) 2015年 CarWorldTeam. All rights reserved.
//
#import "HelperView.h"
#import "HelperTableViewController.h"
#import "HelperModel.h"
#import "HelperTableViewCell.h"
@interface HelperTableViewController ()

@property(nonatomic,retain) NSMutableArray *HelperArray;
@property(nonatomic,retain) WeatherModel *weatherData;
@end

@implementation HelperTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //添加导航栏名称
    self.navigationItem.title = @"我的小助手";
    
    //添加tableView 背景图片
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_fog_bmw.jpg"]];
    //image.backgroundColor = [UIColor redColor];
    [self.tableView setBackgroundView:image];
    [image release];
     self.tableView.showsVerticalScrollIndicator = NO;
    //设置分离符样式
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self getHelper];
    [self getWeather];
   
}

-(void)getHelper
{
    NSURL *url = [NSURL URLWithString:@"http://tq.91.com/api/?act=210&isfamily=0&city=101020900&osv=8.1&dm=iPhone5%2C3&chl=otSy9Zonl%2Fk5CTkt33reOQ%3D%3D&sv=3.7.0&imei=096799B5-A34A-48C8-9457-D38B1DCF93E3&mt=1&nt=10&pid=8032"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[[[NSOperationQueue alloc]init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            //刷新************
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *dic = [[[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil] objectAtIndex:0] objectForKey:@"101020900"];
                NSArray *lifeGuide = dic[@"lifeGuide"];
                self.HelperArray = [NSMutableArray array];
                
                for (NSDictionary *dic1 in lifeGuide)
                {
                    HelperModel *help = [[HelperModel alloc] init];
                    [help setValuesForKeysWithDictionary:dic1];
                    
                    [self.HelperArray addObject:help];
                    
                    [help release];
                    
                }
                [self.tableView reloadData];
            });
            
        }
    }];
}


-(void)getWeather
{
    
    NSURL *url = [NSURL URLWithString:@"http://tq.91.com/api/?act=211&cAct=3&city=101020900&id=pm&mt=1&cityName="];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    static dispatch_once_t onceToken;
    //通常用once 创建单例对象 保证对象的唯一性
    dispatch_once(&onceToken, ^{
        
           [NSURLConnection sendAsynchronousRequest:request queue:[[[NSOperationQueue alloc] init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
         {
             if (data)
             {
                 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                 WeatherModel *weather = [[WeatherModel alloc] init];
                 [weather setValuesForKeysWithDictionary:dic[@"weather"]];
                 self.weatherData = weather;
                 [weather release];
                 
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [self.tableView reloadData];
                 });

             }
         }];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    
    return [_HelperArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 200;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HelperView *headview = [[HelperView alloc] init];
    [headview setHeader:self.weatherData];
    return [headview autorelease];
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"helper";
    HelperTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[[HelperTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier]autorelease];
    }
   
    HelperModel *help = _HelperArray[indexPath.section];
    if (help.photo == nil)
    {
        [help addObserver:self forKeyPath:@"photo" options:(NSKeyValueObservingOptionNew) context:[indexPath retain]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//cell的选择样式
    cell.backgroundColor = [UIColor clearColor];//cell的背景透明
    cell.helper = help;
    
    return cell;
}
//观察者
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSIndexPath *indexPath = (NSIndexPath *)context;
    NSArray *visibleindexpathes = [self.tableView indexPathsForVisibleRows];
    HelperTableViewCell*cell = (HelperTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"+++++++++++++++++++%@",keyPath);
    if ([visibleindexpathes containsObject:indexPath])
    {
        if ([keyPath isEqualToString:@"photo"])
        {
            UIImage *image = [change objectForKey:@"new"];
            cell.iconImageview.image = image;
        }
    }

        [indexPath release];
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
